package com.weacar.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.example.zhouwei.library.CustomPopWindow;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weacar.R;
import com.weacar.activity.BrandSelectActivity;
import com.weacar.activity.CarDetailActivity;
import com.weacar.activity.LoginActivity;
import com.weacar.activity.MainActivity;
import com.weacar.adapter.SearchConditionAdapter;
import com.weacar.adapter.TestAdapter;
import com.weacar.adapter.TimeCountDownAdapter;
import com.weacar.bean.BaseBean;
import com.weacar.bean.CarBean;
import com.weacar.bean.LoginBean;
import com.weacar.config.Constans;
import com.weacar.utils.DesUtil;
import com.weacar.utils.NetWorkUtil;
import com.weacar.utils.SharedPreferenceUtil;
import com.weacar.utils.ToastUtil;
import com.weacar.utils.UserInfoUtil;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;


/**
 * 竞拍大厅
 */

public class AuctionFragment extends Fragment {


    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.iv_age)
    ImageView iv_age;
    @BindView(R.id.iv_price)
    ImageView iv_price;
    @BindView(R.id.tv_brand)
    TextView tv_brand;
    @BindView(R.id.cl_condition)
    ConstraintLayout cl_condition;
    @BindView(R.id.tv_age)
    TextView tv_age;
    @BindView(R.id.tv_price)
    TextView tv_price;
    @BindView(R.id.lv_search_result)
    ListView lv_search_result;
    @BindView(R.id.refresh)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.iv_empty)
    ImageView iv_empty;

    private CustomPopWindow mCustomPopWindow;
    List<CarBean.MsgBean> al;
    private TimeCountDownAdapter timeCountDownAdapter;

    private MainActivity mainActivity;

    private Unbinder unbinder;

    private int myRequestCode = 2;
    private int myRequestCode_5 = 2;

    private int page = 1;
    // 品牌ID
    private int car_id = 0;
    private int date_of_production = 1;
    private int display_price = 1;
    private int refresh_flag = 0;


    @OnClick({R.id.cl_two, R.id.cl_three, R.id.cl_one})
    public void click(View v) {
        switch (v.getId()) {

            case R.id.cl_one:
                Intent intent = new Intent(getActivity(), BrandSelectActivity.class);
                startActivityForResult(intent, myRequestCode);
                break;
            case R.id.cl_two:
                final List<String> al_age = new ArrayList();
                al_age.add("不限年限");
                al_age.add("3年以下");
                al_age.add("3-6年");
                al_age.add("6-10年");
                al_age.add("10年以上");
                showPop(al_age, "age");
                break;
            case R.id.cl_three:
                final List<String> al_price = new ArrayList();
                al_price.add("不限价格");
                al_price.add("5万以下");
                al_price.add("5-10万");
                al_price.add("10-20万");
                al_price.add("20万以上");
                showPop(al_price, "price");
                break;
        }
    }

    // 显示各种条件筛选
    public void showPop(final List<String> al_condition, final String str) {
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.pop_condition_selector, null);
        GridView gv_condition = contentView.findViewById(R.id.gv_condition);

        gv_condition.setAdapter(new SearchConditionAdapter(getActivity(), R.layout.item_gv_key_home, al_condition));
        gv_condition.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                mCustomPopWindow.dissmiss();
                if (str.equals("age")) {
                    tv_age.setText(al_condition.get(i));
                    date_of_production = i + 1;
                } else {
                    tv_price.setText(al_condition.get(i));
                    display_price = i + 1;
                }

                al.clear();
                refresh_flag = 0;
                page = 1;
                if (timeCountDownAdapter != null) {
                    timeCountDownAdapter.notifyDataSetChanged();
                    timeCountDownAdapter.cancelAllTimers();
                }
                getAuctionFormServer();
            }
        });

        mCustomPopWindow = new CustomPopWindow.PopupWindowBuilder(getActivity())
                .setView(contentView)
                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .setBgDarkAlpha(0.7f) // 控制亮度
                .size(ViewGroup.LayoutParams.MATCH_PARENT, 600)//显示大小
                .create()
                .showAsDropDown(cl_condition, 0, 0);
    }


    // 获取竞拍大厅的数据
    public void getAuctionFormServer() {
        if (!NetWorkUtil.isNetworkAvailable(getActivity())) {
            ToastUtil.showShort(getActivity(), "当前网络不可用");
            return;
        }

        try {
            RequestParams params = new RequestParams(Constans.URL_HEADER + Constans.get_auction_search);
            params.setCacheMaxAge(0);
            JSONObject js_request = new JSONObject();
            js_request.put("name", "");
            js_request.put("id", car_id);
            js_request.put("date_of_production", date_of_production);
            js_request.put("display_price", display_price);
            js_request.put("page", page);

            params.setAsJsonContent(true);
            LogUtils.d("Search_params = " + js_request.toString());
            params.setBodyContent(DesUtil.encrypt(js_request.toString()));
            LogUtils.d("Search_url =  " + params.getUri());
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {

                    LogUtils.d("result = " + result);
                    if (refresh_flag == 1) {
                        refreshLayout.finishRefresh();
                    } else if (refresh_flag == 2) {
                        refreshLayout.finishLoadmore();
                    }
                    Gson gson = new Gson();
                    BaseBean baseBean = gson.fromJson(result, BaseBean.class);
                    if (baseBean != null && baseBean.getCode() == 1) {
                        try {
                            CarBean carBean = gson.fromJson(DesUtil.decrypt(baseBean.getData()), CarBean.class);
                            if (carBean != null && carBean.getMsg() != null) {
                                if (refresh_flag == 2 && carBean.getMsg().size() == 0) {
                                    ToastUtil.showShort(getContext(), "没有更多数据了.");
                                } else if (refresh_flag == 0 && carBean.getMsg().size() == 0) {
                                    ToastUtil.showLong(getContext(), "没有查询到数据.");
                                }
                                al.addAll(carBean.getMsg());
                                if (al.size() == 0) {
                                    iv_empty.setVisibility(View.VISIBLE);
                                } else {
                                    iv_empty.setVisibility(View.GONE);
                                }

                                timeCountDownAdapter = new TimeCountDownAdapter(al, getContext());
                                lv_search_result.setAdapter(timeCountDownAdapter);
                                lv_search_result.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                        if (mainActivity.loginBean != null) {
                                            Intent intent = new Intent(getContext(), CarDetailActivity.class);
                                            intent.putExtra("web_url", al.get(i).getWeb_url());
                                            intent.putExtra("car_id", al.get(i).getId());
                                            intent.putExtra("token", UserInfoUtil.getToken(getContext()));
                                            intent.putExtra("auction_type", al.get(i).getAuction_type());
                                            intent.putExtra("online_price", al.get(i).getOnline_price());
                                            startActivity(intent);
                                        } else {
                                            startActivity(new Intent(getActivity(), LoginActivity.class));
                                        }


                                    }
                                });
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        iv_empty.setVisibility(View.VISIBLE);
                        // 错误信息提示
                        if (baseBean != null) {
                            try {
                                com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(DesUtil.decrypt(baseBean.getData()));
                                ToastUtil.showShort(getContext(), jsonObject.get("msg").toString());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            ToastUtil.showShort(getContext(), "系统异常");
                        }
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });


        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.activity_search_result, null);
        unbinder = ButterKnife.bind(this, v);
        iv_back.setVisibility(View.GONE);
        // initData();
        tv_title.setText("竞拍大厅");
        al = new ArrayList();
        mainActivity = (MainActivity) getActivity();
        // 获取竞拍大厅的数据
        getAuctionFormServer();

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                al.clear();
                refresh_flag = 1;
                page = 1;
                if (timeCountDownAdapter != null) {
                    timeCountDownAdapter.cancelAllTimers();
                }
                getAuctionFormServer();

            }
        });

        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                refresh_flag = 2;
                page = page + 1;
                getAuctionFormServer();
            }
        });

        return v;
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (unbinder != null) {
            unbinder.unbind();
        }
        if (timeCountDownAdapter != null) {
            timeCountDownAdapter.cancelAllTimers();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == myRequestCode && resultCode == 3) {
            String result = data.getStringExtra("result");
            int brand_id = data.getIntExtra("brand_id", 0);
            car_id = brand_id;
            LogUtils.d("brand_id = " + brand_id);
            tv_brand.setText(result);
            al.clear();
            refresh_flag = 0;
            page = 1;
            timeCountDownAdapter.notifyDataSetChanged();
            timeCountDownAdapter.cancelAllTimers();
            getAuctionFormServer();
        } else if (requestCode == myRequestCode_5 && resultCode == 3) {
            mainActivity.showMyPriceFragment();
        }
    }
}
